package com.cencat.driver.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cencat.common.result.Result;
import com.cencat.driver.entity.Vehicle;
import com.cencat.driver.service.VehicleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 车辆管理控制器
 * 
 * @author cencat
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/vehicle")
@RequiredArgsConstructor
@Tag(name = "车辆管理", description = "司机端系统 - 车辆信息管理接口")
public class VehicleController {

    private final VehicleService vehicleService;

    @GetMapping("/info/{id}")
    @Operation(summary = "获取车辆信息", description = "根据车辆ID获取车辆详细信息")
    public Result<Vehicle> getVehicleInfo(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Vehicle vehicle = vehicleService.getById(id, tenantId);
            if (vehicle == null) {
                return Result.error("车辆不存在");
            }
            return Result.success(vehicle, "获取车辆信息成功");
        } catch (Exception e) {
            log.error("获取车辆信息异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("获取车辆信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/info/plate/{plateNumber}")
    @Operation(summary = "根据车牌号获取车辆信息", description = "根据车牌号获取车辆详细信息")
    public Result<Vehicle> getVehicleByPlateNumber(
            @Parameter(description = "车牌号", required = true) @PathVariable String plateNumber,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Vehicle vehicle = vehicleService.getByPlateNumber(plateNumber, tenantId);
            if (vehicle == null) {
                return Result.error("车辆不存在");
            }
            return Result.success(vehicle, "获取车辆信息成功");
        } catch (Exception e) {
            log.error("根据车牌号获取车辆信息异常: plateNumber={}, tenantId={}", plateNumber, tenantId, e);
            return Result.error("获取车辆信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/info/code/{vehicleCode}")
    @Operation(summary = "根据车辆编号获取车辆信息", description = "根据车辆编号获取车辆详细信息")
    public Result<Vehicle> getVehicleByCode(
            @Parameter(description = "车辆编号", required = true) @PathVariable String vehicleCode,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Vehicle vehicle = vehicleService.getByVehicleCode(vehicleCode, tenantId);
            if (vehicle == null) {
                return Result.error("车辆不存在");
            }
            return Result.success(vehicle, "获取车辆信息成功");
        } catch (Exception e) {
            log.error("根据车辆编号获取车辆信息异常: vehicleCode={}, tenantId={}", vehicleCode, tenantId, e);
            return Result.error("获取车辆信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/driver/{driverId}")
    @Operation(summary = "获取司机车辆列表", description = "根据司机ID获取其名下的车辆列表")
    public Result<List<Vehicle>> getVehiclesByDriverId(
            @Parameter(description = "司机ID", required = true) @PathVariable Long driverId,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            List<Vehicle> vehicles = vehicleService.getByDriverId(driverId, tenantId);
            return Result.success(vehicles, "获取司机车辆列表成功");
        } catch (Exception e) {
            log.error("获取司机车辆列表异常: driverId={}, tenantId={}", driverId, tenantId, e);
            return Result.error("获取司机车辆列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获取车辆列表", description = "分页获取车辆列表，支持多条件筛选")
    public Result<IPage<Vehicle>> getVehicleList(
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "车牌号") @RequestParam(required = false) String plateNumber,
            @Parameter(description = "车辆编号") @RequestParam(required = false) String vehicleCode,
            @Parameter(description = "车辆类型") @RequestParam(required = false) Integer vehicleType,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "司机ID") @RequestParam(required = false) Long driverId,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            IPage<Vehicle> result = vehicleService.getPageList(current, size, plateNumber, vehicleCode, vehicleType, status, driverId, tenantId);
            return Result.success(result, "获取车辆列表成功");
        } catch (Exception e) {
            log.error("获取车辆列表异常: tenantId={}", tenantId, e);
            return Result.error("获取车辆列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/available")
    @Operation(summary = "获取可用车辆列表", description = "获取当前可用的车辆列表（空闲状态）")
    public Result<List<Vehicle>> getAvailableVehicles(
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            List<Vehicle> result = vehicleService.getAvailableVehicles(tenantId);
            return Result.success(result, "获取可用车辆列表成功");
        } catch (Exception e) {
            log.error("获取可用车辆列表异常: tenantId={}", tenantId, e);
            return Result.error("获取可用车辆列表失败: " + e.getMessage());
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建车辆", description = "创建新的车辆记录")
    public Result<Boolean> createVehicle(
            @Parameter(description = "车辆信息", required = true) @Valid @RequestBody Vehicle vehicle) {
        try {
            boolean result = vehicleService.createVehicle(vehicle);
            return Result.success(result, "创建车辆成功");
        } catch (Exception e) {
            log.error("创建车辆异常: plateNumber={}, vehicleCode={}, tenantId={}", 
                     vehicle.getPlateNumber(), vehicle.getVehicleCode(), vehicle.getTenantId(), e);
            return Result.error("创建车辆失败: " + e.getMessage());
        }
    }

    @PutMapping("/update")
    @Operation(summary = "更新车辆信息", description = "更新车辆基本信息")
    public Result<Boolean> updateVehicle(
            @Parameter(description = "车辆信息", required = true) @Valid @RequestBody Vehicle vehicle) {
        try {
            boolean result = vehicleService.updateVehicle(vehicle);
            return Result.success(result, "更新车辆信息成功");
        } catch (Exception e) {
            log.error("更新车辆信息异常: id={}, tenantId={}", vehicle.getId(), vehicle.getTenantId(), e);
            return Result.error("更新车辆信息失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除车辆", description = "删除指定车辆")
    public Result<Boolean> deleteVehicle(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.deleteVehicle(id, tenantId);
            return Result.success(result, "删除车辆成功");
        } catch (Exception e) {
            log.error("删除车辆异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("删除车辆失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除车辆", description = "批量删除多个车辆")
    public Result<Boolean> batchDeleteVehicles(
            @Parameter(description = "车辆ID列表", required = true) @RequestBody List<Long> ids,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.batchDeleteVehicles(ids, tenantId);
            return Result.success(result, "批量删除车辆成功");
        } catch (Exception e) {
            log.error("批量删除车辆异常: tenantId={}", tenantId, e);
            return Result.error("批量删除车辆失败: " + e.getMessage());
        }
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新车辆状态", description = "更新车辆的启用/禁用状态")
    public Result<Boolean> updateVehicleStatus(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "状态", required = true) @RequestParam Integer status,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.updateStatus(id, status, tenantId);
            return Result.success(result, "更新车辆状态成功");
        } catch (Exception e) {
            log.error("更新车辆状态异常: id={}, status={}, tenantId={}", id, status, tenantId, e);
            return Result.error("更新车辆状态失败: " + e.getMessage());
        }
    }

    @PostMapping("/assign-driver")
    @Operation(summary = "分配司机", description = "为车辆分配司机")
    public Result<Boolean> assignDriver(
            @Parameter(description = "车辆ID", required = true) @RequestParam Long vehicleId,
            @Parameter(description = "司机ID", required = true) @RequestParam Long driverId,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.assignDriver(vehicleId, driverId, tenantId);
            return Result.success(result, "分配司机成功");
        } catch (Exception e) {
            log.error("分配司机异常: vehicleId={}, driverId={}, tenantId={}", vehicleId, driverId, tenantId, e);
            return Result.error("分配司机失败: " + e.getMessage());
        }
    }

    @PostMapping("/unassign-driver")
    @Operation(summary = "取消分配司机", description = "取消车辆的司机分配")
    public Result<Boolean> unassignDriver(
            @Parameter(description = "车辆ID", required = true) @RequestParam Long vehicleId,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.unassignDriver(vehicleId, tenantId);
            return Result.success(result, "取消分配司机成功");
        } catch (Exception e) {
            log.error("取消分配司机异常: vehicleId={}, tenantId={}", vehicleId, tenantId, e);
            return Result.error("取消分配司机失败: " + e.getMessage());
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取车辆统计信息", description = "获取车辆相关的统计数据")
    public Result<Map<String, Object>> getStatistics(
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Map<String, Object> result = vehicleService.getStatistics(tenantId);
            return Result.success(result, "获取车辆统计信息成功");
        } catch (Exception e) {
            log.error("获取车辆统计信息异常: tenantId={}", tenantId, e);
            return Result.error("获取车辆统计信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/maintenance/{id}")
    @Operation(summary = "获取车辆维护记录", description = "获取指定车辆的维护记录")
    public Result<List<Map<String, Object>>> getVehicleMaintenance(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            List<Map<String, Object>> result = vehicleService.getVehicleMaintenance(id, startDate, endDate, tenantId);
            return Result.success(result, "获取车辆维护记录成功");
        } catch (Exception e) {
            log.error("获取车辆维护记录异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("获取车辆维护记录失败: " + e.getMessage());
        }
    }

    @PostMapping("/maintenance")
    @Operation(summary = "添加维护记录", description = "为车辆添加维护记录")
    public Result<Boolean> addMaintenanceRecord(
            @Parameter(description = "车辆ID", required = true) @RequestParam Long vehicleId,
            @Parameter(description = "维护类型", required = true) @RequestParam String maintenanceType,
            @Parameter(description = "维护内容", required = true) @RequestParam String content,
            @Parameter(description = "维护费用") @RequestParam(required = false) Double cost,
            @Parameter(description = "维护人员") @RequestParam(required = false) String maintainer,
            @Parameter(description = "备注") @RequestParam(required = false) String remark,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.addMaintenanceRecord(vehicleId, maintenanceType, content, cost, maintainer, remark, tenantId);
            return Result.success(result, "添加维护记录成功");
        } catch (Exception e) {
            log.error("添加维护记录异常: vehicleId={}, tenantId={}", vehicleId, tenantId, e);
            return Result.error("添加维护记录失败: " + e.getMessage());
        }
    }

    @GetMapping("/usage/{id}")
    @Operation(summary = "获取车辆使用情况", description = "获取指定车辆的使用情况统计")
    public Result<Map<String, Object>> getVehicleUsage(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Map<String, Object> result = vehicleService.getVehicleUsage(id, startDate, endDate, tenantId);
            return Result.success(result, "获取车辆使用情况成功");
        } catch (Exception e) {
            log.error("获取车辆使用情况异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("获取车辆使用情况失败: " + e.getMessage());
        }
    }

    @GetMapping("/export")
    @Operation(summary = "导出车辆信息", description = "导出车辆信息到Excel")
    public Result<List<Map<String, Object>>> exportVehicles(
            @Parameter(description = "车牌号") @RequestParam(required = false) String plateNumber,
            @Parameter(description = "车辆编号") @RequestParam(required = false) String vehicleCode,
            @Parameter(description = "车辆类型") @RequestParam(required = false) Integer vehicleType,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "司机ID") @RequestParam(required = false) Long driverId,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            List<Map<String, Object>> result = vehicleService.exportVehicles(plateNumber, vehicleCode, vehicleType, status, driverId, tenantId);
            return Result.success(result, "导出车辆信息成功");
        } catch (Exception e) {
            log.error("导出车辆信息异常: tenantId={}", tenantId, e);
            return Result.error("导出车辆信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/import")
    @Operation(summary = "导入车辆信息", description = "从Excel导入车辆信息")
    public Result<Map<String, Object>> importVehicles(
            @Parameter(description = "车辆数据列表", required = true) @RequestBody List<Map<String, Object>> vehicleList,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Map<String, Object> result = vehicleService.importVehicles(vehicleList, tenantId);
            return Result.success(result, "导入车辆信息完成");
        } catch (Exception e) {
            log.error("导入车辆信息异常: tenantId={}", tenantId, e);
            return Result.error("导入车辆信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/batch-assign-driver")
    @Operation(summary = "批量分配司机", description = "批量为车辆分配司机")
    public Result<Map<String, Object>> batchAssignDriver(
            @Parameter(description = "车辆司机分配列表", required = true) @RequestBody List<Map<String, Object>> assignList,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Map<String, Object> result = vehicleService.batchAssignDriver(assignList, tenantId);
            return Result.success(result, "批量分配司机完成");
        } catch (Exception e) {
            log.error("批量分配司机异常: tenantId={}", tenantId, e);
            return Result.error("批量分配司机失败: " + e.getMessage());
        }
    }

    @PostMapping("/batch-update-status")
    @Operation(summary = "批量更新车辆状态", description = "批量更新多个车辆的状态")
    public Result<Boolean> batchUpdateStatus(
            @Parameter(description = "车辆ID列表", required = true) @RequestBody List<Long> ids,
            @Parameter(description = "状态", required = true) @RequestParam Integer status,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.batchUpdateStatus(ids, status, tenantId);
            return Result.success(result, "批量更新车辆状态成功");
        } catch (Exception e) {
            log.error("批量更新车辆状态异常: status={}, tenantId={}", status, tenantId, e);
            return Result.error("批量更新车辆状态失败: " + e.getMessage());
        }
    }

    @GetMapping("/performance/{id}")
    @Operation(summary = "获取车辆绩效信息", description = "获取指定车辆的绩效数据")
    public Result<Map<String, Object>> getVehiclePerformance(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Map<String, Object> result = vehicleService.getVehiclePerformance(id, startDate, endDate, tenantId);
            return Result.success(result, "获取车辆绩效信息成功");
        } catch (Exception e) {
            log.error("获取车辆绩效信息异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("获取车辆绩效信息失败: " + e.getMessage());
        }
    }

    @GetMapping("/fuel-consumption/{id}")
    @Operation(summary = "获取车辆油耗信息", description = "获取指定车辆的油耗统计")
    public Result<Map<String, Object>> getVehicleFuelConsumption(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            Map<String, Object> result = vehicleService.getVehicleFuelConsumption(id, startDate, endDate, tenantId);
            return Result.success(result, "获取车辆油耗信息成功");
        } catch (Exception e) {
            log.error("获取车辆油耗信息异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("获取车辆油耗信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/fuel-record")
    @Operation(summary = "添加加油记录", description = "为车辆添加加油记录")
    public Result<Boolean> addFuelRecord(
            @Parameter(description = "车辆ID", required = true) @RequestParam Long vehicleId,
            @Parameter(description = "加油量(升)", required = true) @RequestParam Double fuelAmount,
            @Parameter(description = "加油费用", required = true) @RequestParam Double cost,
            @Parameter(description = "当前里程") @RequestParam(required = false) Double mileage,
            @Parameter(description = "加油站") @RequestParam(required = false) String gasStation,
            @Parameter(description = "备注") @RequestParam(required = false) String remark,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.addFuelRecord(vehicleId, fuelAmount, cost, mileage, gasStation, remark, tenantId);
            return Result.success(result, "添加加油记录成功");
        } catch (Exception e) {
            log.error("添加加油记录异常: vehicleId={}, tenantId={}", vehicleId, tenantId, e);
            return Result.error("添加加油记录失败: " + e.getMessage());
        }
    }

    @GetMapping("/inspection/{id}")
    @Operation(summary = "获取车辆检查记录", description = "获取指定车辆的检查记录")
    public Result<List<Map<String, Object>>> getVehicleInspection(
            @Parameter(description = "车辆ID", required = true) @PathVariable Long id,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            List<Map<String, Object>> result = vehicleService.getVehicleInspection(id, startDate, endDate, tenantId);
            return Result.success(result, "获取车辆检查记录成功");
        } catch (Exception e) {
            log.error("获取车辆检查记录异常: id={}, tenantId={}", id, tenantId, e);
            return Result.error("获取车辆检查记录失败: " + e.getMessage());
        }
    }

    @PostMapping("/inspection")
    @Operation(summary = "添加检查记录", description = "为车辆添加检查记录")
    public Result<Boolean> addInspectionRecord(
            @Parameter(description = "车辆ID", required = true) @RequestParam Long vehicleId,
            @Parameter(description = "检查类型", required = true) @RequestParam String inspectionType,
            @Parameter(description = "检查结果", required = true) @RequestParam String result,
            @Parameter(description = "检查人员") @RequestParam(required = false) String inspector,
            @Parameter(description = "问题描述") @RequestParam(required = false) String issues,
            @Parameter(description = "备注") @RequestParam(required = false) String remark,
            @Parameter(description = "租户ID", required = true) @RequestParam Long tenantId) {
        try {
            boolean result = vehicleService.addInspectionRecord(vehicleId, inspectionType, result, inspector, issues, remark, tenantId);
            return Result.success(result, "添加检查记录成功");
        } catch (Exception e) {
            log.error("添加检查记录异常: vehicleId={}, tenantId={}", vehicleId, tenantId, e);
            return Result.error("添加检查记录失败: " + e.getMessage());
        }
    }
}